const fs = require("fs");
const path = require('path');
const child_process = require('child_process');

// 同步执行exec
child_process.execPromise = (cmd, options, callback) => {
    return new Promise<void>((resolve, reject) => {
        child_process.exec(cmd, options, (err, stdout, stderr) => {
            if (err) {
                reject(err);
            }
            resolve();
        })
    });
};

export default class app {
    private static assetUrlArr = [];//缓存.meta文件路径

    public static async run(assetUrl) {
        await this.readFileList(assetUrl);
        await this.deleteMeta();
        console.log('删除完毕');
    }

    /**
     * 递归检测出所有资源
     * @param url 目标路径
     */
    private static readFileList(url) {
        const stat = fs.statSync(url);
        if (stat.isDirectory()) {
            // this.logInfo('文件夹');
            let files = fs.readdirSync(url, "utf-8");
            files = files.filter((file) => {
                var fullPath = path.join(url, file);
                this.detectionType(fullPath);
                return !file.endsWith(".meta");
            });
            files.forEach((item, index) => {
                var fullPath = path.join(url, item);
                const stat = fs.statSync(fullPath);
                if (stat.isDirectory()) {
                    //如果文件夹内还包含文件夹，那么继续读取这个文件夹内的内容
                    this.readFileList(path.join(url, item));  //递归读取文件
                } else {
                    this.detectionType(fullPath);
                }
            });
            this.detectionType(url);
            return;
        } else {
            this.detectionType(url);
        }
    }

    //检测文件类型
    private static detectionType(url) {
        if (url.endsWith(".meta")) {
            this.assetUrlArr.push(url);
        }
    }

    //删除meta文件
    private static deleteMeta() {
        for (let i = 0;i < this.assetUrlArr.length;i++) {
            fs.unlinkSync(this.assetUrlArr[i]);
        }
    }
}

let assetUrl = process.argv[2];
app.run(assetUrl);